<?php
declare (strict_types=1);

namespace app\controller\home;

use app\common\controller\BaseController;
use app\model\home\Order as orderModel;
use think\App;
use \Throwable;

class Order extends BaseController
{
    protected $model;

    public function __construct(App $app, orderModel $model)
    {
        parent::__construct($app);
        $this->model = $model;
    }

    /**
     * 列表查询
     * @return array
     */
    public function query()
    {
        $where = [];
        $page = input('page/d', 1);
        $pageSize = input('page_size/d', 20);
        $orderType = input('order_type/d', 1);
        $where['member_id'] = $this->memberId;
        $where['order_type'] = $orderType;
        $order = null;
        $fields = 'id,order_no,re_id,store_id,store_id store_name,order_type,order_type order_type_str,pay_price,pay_status,pay_time';
        return $this->model->getList($where, $fields, $order, $page, $pageSize);
    }

    /**
     * @return array
     * 创建订单
     */
    public function create()
    {
        try {
            $this->params['member_id'] = $this->memberId;
            return $this->model->createOrder($this->params);
        } catch (\Exception $ex) {
            return $this->returnException($ex);
        }
    }

    /**
     * @return mixed
     * 更新订单信息
     */
    public function update()
    {
        try {
            validate(\app\validate\home\Order::class)->scene('update')->check($this->params);
            return $this->model->updateOrder($this->params);
        } catch (\Exception $ex) {
            return $this->returnException($ex);
        }
    }

    /**
     * @return mixed
     * 购物车
     */
    public function mycart()
    {
        $where = [];
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['pay_status', '=', 0];
        $where[] = ['is_cart', '=', 1];
        $where[] = ['order_type', '<>', 6];
        $order = ['create_time' => 'DESC'];
        $field = "id,order_no,member_id,re_id,book_id,store_id,store_id store_name,order_count,order_type,order_type order_type_str,pay_price,create_time";
        $page = input('page/d', 1);
        $pageSize = input('page_size/d', 10);
        return $this->model->getMyCart($where, $field, $order, $page, $pageSize);
    }

    /**
     * @return array
     * 余额支付
     */
    public function balancePay()
    {
        try {
            $this->params['member_id'] = $this->memberId;
            return $this->model->payWithBalance($this->params);
        } catch (\Exception $ex) {
            return $this->returnException($ex);
        }
    }

    /**
     * @return array
     * 清空购物车
     */
    public function clearCart()
    {
        try {
            return $this->model->clearData($this->params);
        } catch (\Exception $ex) {
            return $this->returnException($ex);
        }
    }
}
